/*
 * @Author: mingfeng (SunnyQjm)
 * @Date: 2023-09-19 15:23:44
 * @Description: 
 */

import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { useRef } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { Tag, Space, message } from 'antd';
import { JsonView, allExpanded, darkStyles, defaultStyles } from 'react-json-view-lite';
import 'react-json-view-lite/dist/index.css';
import { getAlarmDataList, markAlarmDataAsRead } from '../service'


/**
 * 
 * @returns 
 * @reference 
 *  - https://procomponents.ant.design/components/schema#valuetype
 */
const AlarmDataList = () => {
    const intl = useIntl();
    const alarmDataTableRef = useRef();
    const columns = [
        {
            title: <FormattedMessage id="pages.alarm.list.alert_id" defaultMessage="ID" />,
            dataIndex: 'alert_id',
            valueType: 'textarea',
            copyable: true,
        },
        {
            title: <FormattedMessage id="pages.alarm.list.alert_instance" defaultMessage="Instance" />,
            dataIndex: 'instance',
            valueType: 'textarea',
            copyable: true,
        },
        {
            title: <FormattedMessage id="pages.alarm.list.alert_item" defaultMessage="Item" />,
            dataIndex: 'alert_item',
            valueType: 'textarea',
            filters: true,
            sorter: (a, b) => {
                if (a.alert_item === undefined) {
                    return -1
                } else if (b.alert_item === undefined) {
                    return 1;
                } else {
                    return String(a.alert_item).localeCompare(String(b.alert_item));
                }
            }
        },
        {
            title: <FormattedMessage id="pages.alarm.list.alert_category" defaultMessage="Category" />,
            dataIndex: 'alert_category',
            filters: true,
            valueEnum: {
                "MONITOR": {
                    text: (
                        <FormattedMessage id="pages.alarm.list.alert_category_monitor" defaultMessage="Unread" />
                    ),
                },
                "APPLICATION": {
                    text: (
                        <FormattedMessage id="pages.alarm.list.alert_category_application" defaultMessage="Readed" />
                    ),
                },
                "OTHER": {
                    text: (
                        <FormattedMessage id="pages.alarm.list.alert_category_other" defaultMessage="Merged" />
                    ),
                },
            },
        },
        {
            title: <FormattedMessage id="pages.alarm.list.alert_labels" defaultMessage="Labels" />,
            dataIndex: 'labels',
            valueType: 'textarea',

            render: (dom, entity, index, action, schema) => {
                // render labels
                let label_elements = [];
                Object.keys(entity.labels).forEach((k) => {
                    label_elements.push(
                        <Tag key={k}>{k}={entity.labels[k]}</Tag>
                    )
                })
                return <Space size={[0, 'small']} wrap>
                    {
                        label_elements
                    }
                </Space>
            }
        },
        {
            title: <FormattedMessage id="pages.alarm.list.alert_deal_status" defaultMessage="Deal Status" />,
            dataIndex: 'deal_status',
            filters: true,
            valueEnum: {
                "0": {
                    text: (
                        <FormattedMessage id="pages.alarm.list.alert_deal_status_unread" defaultMessage="Unread" />
                    ),
                    status: 'Default',
                },
                "1": {
                    text: (
                        <FormattedMessage id="pages.alarm.list.alert_deal_status_readed" defaultMessage="Readed" />
                    ),
                    status: 'Success',
                },
                "2": {
                    text: (
                        <FormattedMessage id="pages.alarm.list.alert_deal_status_merged" defaultMessage="Merged" />
                    ),
                    status: 'Success',
                },
            },
        },
        {
            title: <FormattedMessage id="pages.alarm.list.alert_time" defaultMessage="Time" />,
            dataIndex: 'alert_time',
            valueType: 'dateTime',
            sorter: (a, b) => a.alert_time - b.alert_time,
        },
        {
            title: <FormattedMessage id="pages.alarm.list.operating" defaultMessage="Operating" />,
            key: 'option',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => {
                let operations = []

                // 1. Add mark as read operation
                if (record.deal_status == 0) {
                    operations.push(<span key='mark_as_read'>
                        {
                            <a onClick={() => {
                                markAlarmDataAsRead([record.id])
                                    .then(res => {
                                        if (alarmDataTableRef.current) {
                                            alarmDataTableRef.current.reload()
                                        }
                                    })
                            }}>
                                <FormattedMessage id="pages.alarm.list.mark_as_read" defaultMessage="Mark as read" />
                            </a>
                        }
                    </span>)
                }


                // 2. Add extra operations
                Object.keys(record.annotations).filter(v => v.startsWith("SYSOM_ALARM:OPT")).forEach(k => {
                    let operation = record.annotations[k];
                    switch (operation.type) {
                        case "LINK":
                            operations.push(<span key={k}>
                                {
                                    <a onClick={() => {
                                        window.open(operation.url)
                                    }}>
                                        {intl.formatMessage({
                                            id: operation.label,
                                            defaultMessage: operation.label
                                        })}
                                    </a>
                                }
                            </span>)
                            break
                        case "DIAGNOSIS":
                            operations.push(<span key={k}>
                                {
                                    <a onClick={() => {
                                        message.warning("Not support DIAGNOSIS opt now!")
                                    }}>
                                        {intl.formatMessage({
                                            id: operation.label,
                                            defaultMessage: operation.label
                                        })}
                                    </a>
                                }
                            </span>)
                            break
                    }

                })
                return operations
            },
        }
    ]
    return (
        <PageContainer>
            <ProTable
                actionRef={alarmDataTableRef}
                rowKey="id"
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [
                ]}
                pagination={{ showSizeChanger: true, pageSizeOptions: [10, 20], defaultPageSize: 10 }}
                request={async (params, sort, filter) => {
                    if (Object.keys(sort).length != 0) {
                        const sort_key = Object.keys(sort)[0];
                        const _sort = sort[sort_key] === "ascend" ? sort_key : `-${sort_key}`
                        params['sort__'] = _sort
                    }
                    // if (filter.event_type) {
                    //     params['event_type'] = filter.event_type.join(",")
                    // }
                    Object.keys(filter).forEach(k => {
                        if (!!filter[k]) {
                            params[k] = filter[k].join(",")
                        }
                    })
                    const result = await getAlarmDataList(params)
                    return result
                }}
                columns={columns}
                rowSelection={{
                    defaultSelectedRowKeys: [],
                }}
                tableAlertOptionRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => {
                    return (
                        <Space size={16}>
                            <a
                                onClick={async () => {
                                    markAlarmDataAsRead(selectedRowKeys)
                                        .then(res => {
                                            if (alarmDataTableRef.current) {
                                                alarmDataTableRef.current.reload()
                                            }
                                            onCleanSelected()
                                        })
                                }}
                            >
                                <FormattedMessage id="pages.alarm.list.mark_as_read" defaultMessage="Mark as read" />
                            </a>
                        </Space>
                    );
                }}
            expandable={{
                expandedRowRender: (record) => (
                    <p><JsonView data={record.annotations} shouldExpandNode={allExpanded} style={{
                        ...darkStyles,
                        container: ""
                    }} /></p>
                ),
                showExpandColumn: true,
            }}
            />
        </PageContainer>
    )
}

export default AlarmDataList;
